﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using Kugar.Core.Enums;
using Kugar.Core.Collections;
using Kugar.Core.ExtMethod;

namespace Kugar.ERPFramework.View.WinForm
{
    /// <summary>
    ///     控件读取窗口基类
    /// </summary>
    public class DataFetcherManager
    {
        private ListEx<DataFetcherFillMapping> _dataFetchMapping = new ListEx<DataFetcherFillMapping>();
        private List<DataFetcherInitMapping> _dataFetherInitParamMapping = new List<DataFetcherInitMapping>();
        private FieldConfig _field = null;
        private string _dataFetcherName = null;

        public DataFetcherManager(FieldConfig field)
        {
            if (field == null)
            {
                throw new ArgumentNullException("field");
            }

            _field = field;

            _dataFetchMapping = new ListEx<DataFetcherFillMapping>();
            _dataFetchMapping.CollectionChanged += lst_CollectionChanged;

            DataFetherEnabled = EnabledEx.Auto;
        }

        public bool HasDataFether
        {
            get
            {
                if (DataFetherEnabled == EnabledEx.Auto)
                {
                    return !string.IsNullOrWhiteSpace(DataFetcherName) && _dataFetchMapping.Count > 0;
                }
                else
                {
                    return DataFetherEnabled == EnabledEx.Enabled;
                }
            }
        }

        public IList<DataFetcherFillMapping> DataFetchMapping { get { return _dataFetchMapping; } }

        public IList<DataFetcherInitMapping> DataFetherInitParamMapping { get { return _dataFetherInitParamMapping; } }

        public void Show()
        {
            OnOpenDataFether(_dataFetcherName, null);
        }

        public bool EnableMultiSelect { set; get; }

        private EnabledEx _dataFetherEnabled = EnabledEx.Auto;
        public EnabledEx DataFetherEnabled
        {
            set
            {
                if (_dataFetherEnabled != value)
                {
                    _dataFetherEnabled = value;

                    OnDataFetherChanged();
                }
            }
            get { return _dataFetherEnabled; }
        }

        public event EventHandler DataFetherEnabledChanged;

        public event EventHandler<CancelEventArgs> BeforeDataFetcher;

        public event EventHandler DataFetherCompleted;

        /// <summary>
        ///     默认的取数窗口名称
        /// </summary>
        public string DataFetcherName
        {
            set
            {
                if (_dataFetcherName != value)
                {
                    _dataFetcherName = value;

                    OnDataFetherChanged();
                }
            }
            get { return _dataFetcherName; }
        }

        protected virtual void OnDataFetherChanged()
        {
            if (DataFetherEnabledChanged != null)
            {
                DataFetherEnabledChanged(this, EventArgs.Empty);
            }
        }

        /// <summary>
        ///     打开取数窗口
        /// </summary>
        /// <param name="dataFetherName">允许运行时再确定取数窗口名称,如果为空,则使用对象内DataFetherName属性值</param>
        /// <param name="enableMultiSelect">是否允许多选,默认为false</param>
        /// <param name="initArgs">初始化参数,如果传null,,则使用 DataFetherInitParamMapping 映射的关系读取初始化值</param>
        protected virtual void OnOpenDataFether(string dataFetherName, Dictionary<string, object> initArgs = null)
        {
            if (BeforeDataFetcher!=null)
            {
                var e = new CancelEventArgs(false);

                BeforeDataFetcher(this, e);

                if (e.Cancel)
                {
                    return;
                }
            }

            if ((initArgs == null || initArgs.Count <= 0) && DataFetherInitParamMapping.Count > 0)
            {
                initArgs = new Dictionary<string, object>();

                foreach (var mapping in DataFetherInitParamMapping)
                {
                    if (!initArgs.ContainsKey(mapping.ArgsName))
                    {
                        try
                        {
                            var v = _field.Manager.GetValue(mapping.FieldID);

                            initArgs.Add(mapping.ArgsName, v);
                        }
                        catch (Exception)
                        {

                        }
                    }
                }
            }

            var dataList = ClientBroker.GetInstance().ShowDataFetcher(dataFetherName, EnableMultiSelect, initArgs);

            if (dataList != null && dataList.Length > 0)
            {
                AfterDataFetherCompleted(dataList);
            }
        }

        protected virtual void AfterDataFetherCompleted(object[] fetherData)
        {
            if (_field.Manager != null && DataFetchMapping.Count > 0 && fetherData != null)
            {
                FillData(_field.Manager, fetherData.FirstOrDefault());
            }

            OnDataFetherCompleted();
        }

        /// <summary>
        ///     取数窗口读取完数据之后,返回时调用该函数进行填充,如果允许返回列表值,则重载该函数后,进行处理
        /// </summary>
        /// <param name="fetherData"></param>
        protected virtual void OnDataFetherCompleted()
        {
            if (DataFetherCompleted != null)
            {
                DataFetherCompleted(this, EventArgs.Empty);
            }
        }

        /// <summary>
        ///     取数窗口读取完数据后,使用该参数进行单个值的填充,可以重载后,改变单个值填充的方式
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="fethData"></param>
        protected virtual void FillData(FieldsManager manager, object fethData)
        {
            foreach (var mappingItem in DataFetchMapping)
            {
                var value = fethData.FastGetValue(mappingItem.SourceFieldName);

                manager.SetValue(mappingItem.TargetID, value);
            }
        }

        private void lst_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs<DataFetcherFillMapping> e)
        {
            OnDataFetherChanged();
        }
    }

    public class DetailDataFetherManager: DataFetcherManager
    {
        public DetailDataFetherManager(FieldConfig field) : base(field)
        {
        }

        protected override void AfterDataFetherCompleted(object[] fetherData)
        {



            base.OnDataFetherCompleted();
        }

        private  void FillData(FieldsManager manager, object[] fethData)
        {
            base.FillData(manager, fethData);
        }
    }

    /// <summary>
    ///     取数后,自动填充的映射关系
    /// </summary>
    public class DataFetcherFillMapping
    {
        /// <summary>
        ///     数据源对象字段名
        /// </summary>
        public string SourceFieldName { set; get; }

        /// <summary>
        ///     填充的目标ID
        /// </summary>
        public string TargetID { set; get; }
    }

    /// <summary>
    ///     取数窗口初始化时需要提供的初始化参数映射关系
    /// </summary>
    public class DataFetcherInitMapping
    {
        /// <summary>
        ///     参数名称
        /// </summary>
        public string ArgsName { set; get; }

        /// <summary>
        ///     提供数据的字段ID
        /// </summary>
        public string FieldID { set; get; }
    }
}
